package service;

import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import beans.Agent;
import beans.Branch;
import beans.Courier;
import beans.Goods;
import beans.LogAbnormalBox;
import beans.LogAbnormalParcel;
import beans.LogParcel;
import beans.Package;
import beans.Terminal;

import dao.BoxDao;
import dao.BranchDao;
import dao.CourierDao;
import dao.GoodsDao;
import dao.LogParcelDao;
import dao.PackageDao;
import dao.QueryDAO;
import dao.TerminalDao;

import utils.CalculateDate;
import utils.GetHelper;
import utils.PageBean;


public class BoxAndPackageService implements BoxAndPackageServiceInterface {
	BoxDao boxDao = new BoxDao();
	PackageDao packageDao = new PackageDao();
	LogParcelDao logParcelDao = new LogParcelDao();
	GoodsDao goodsDao = new GoodsDao();
	TerminalDao terminalDao = new TerminalDao();
	QueryDAO queryDAO = new QueryDAO();
	BranchDao branchDao = new BranchDao();
	CourierDao courierDao = new CourierDao();

	@Override
	public void updateBoxRemark(Terminal terminal) {
		String sql = "update boxstatus set boxStatus_boxRemark = 0 where boxStatus_terminalID = ? and boxStatus_isdelete = 0";
		queryDAO.queryExcute(sql, terminal.getTerminalId());
		sql = "select count(*) from boxstatus where boxStatus_terminalID = ? and boxStatus_boxTypeID = ? and boxStatus_isdelete = 0;";
		BigInteger superBoxNum = (BigInteger) queryDAO.querySelect(sql,
				terminal.getTerminalId(), 1).get(0);
		BigInteger bigBoxNum = (BigInteger) queryDAO.querySelect(sql,
				terminal.getTerminalId(), 2).get(0);
		BigInteger mediumBoxNum = (BigInteger) queryDAO.querySelect(sql,
				terminal.getTerminalId(), 3).get(0);
		BigInteger smallBoxNum = (BigInteger) queryDAO.querySelect(sql,
				terminal.getTerminalId(), 4).get(0);
		if (superBoxNum.intValue() > 0) {
			sql = "update boxstatus set boxStatus_boxRemark = 1 where boxStatus_terminalID = ? and boxStatus_boxTypeID = ? and boxStatus_isdelete = 0 order by boxStatus_id asc limit "
					+ superBoxNum.intValue() * terminal.getSuperReserve() / 100;
			queryDAO.queryExcute(sql, terminal.getTerminalId(), 1);
		}
		if (bigBoxNum.intValue() > 0) {
			sql = "update boxstatus set boxStatus_boxRemark = 1 where boxStatus_terminalID = ? and boxStatus_boxTypeID = ? and boxStatus_isdelete = 0 order by boxStatus_id asc limit "
					+ bigBoxNum.intValue() * terminal.getBigReserve() / 100;
			queryDAO.queryExcute(sql, terminal.getTerminalId(), 2);
		}
		if (mediumBoxNum.intValue() > 0) {
			sql = "update boxstatus set boxStatus_boxRemark = 1 where boxStatus_terminalID = ? and boxStatus_boxTypeID = ? and boxStatus_isdelete = 0 order by boxStatus_id asc limit "
					+ mediumBoxNum.intValue()
					* terminal.getMediumReserve()
					/ 100;
			queryDAO.queryExcute(sql, terminal.getTerminalId(), 3);
		}
		if (smallBoxNum.intValue() > 0) {
			sql = "update boxstatus set boxStatus_boxRemark = 1 where boxStatus_terminalID = ? and boxStatus_boxTypeID = ? and boxStatus_isdelete = 0 order by boxStatus_id asc limit "
					+ smallBoxNum.intValue() * terminal.getSmallReserve() / 100;
			queryDAO.queryExcute(sql, terminal.getTerminalId(), 4);
		}
	}

	@Override
	public void clearBox(int terminalID, int boxNum) {
		String sql = "update boxstatus set boxStatus_status = 0 where boxStatus_terminalID = ? and boxStatus_boxNum = ? and boxStatus_isdelete = 0";
		queryDAO.queryExcute(sql, terminalID, boxNum);
	}

	@Override
	public List<LogAbnormalParcel> findAbnormalParcel(int terminalID, int boxNum) {
		String hql = "from LogAbnormalParcel l where l.terminal.terminalId = ? and l.boxNum = ? order by l.time desc limit 5";
		return queryDAO.query(hql, terminalID, String.valueOf(boxNum));
	}

	@Override
	public List<LogAbnormalBox> findAbnormalBox(int terminalID, int boxNum) {
		String hql = "from LogAbnormalBox l where l.terminal.terminalId = ? and l.boxNum = ? order by l.time desc limit 5";
		return queryDAO.query(hql, terminalID, String.valueOf(boxNum));
	}

	@Override
	public PageBean<Package> getUnTakenPakcages(int curpage, int pageSize,
			int agentID, int branchID, int terminalID, int day) {
		StringBuffer buffer = new StringBuffer();
		Timestamp timestamp = new Timestamp(CalculateDate.getDateBeforeByDay(
				new Date(), day - 1).getTime());
		if (terminalID != -1) {
			buffer.append(" and p.terminal.terminalId = " + terminalID);
		} else {
			if (branchID != -1) {
				buffer.append(" and p.terminal.branch.branchId = " + branchID);
			} else {
				if (agentID != -1) {
					buffer.append(" and p.terminal.branch.agent.id = "
							+ agentID);
				}
			}
		}
		String hql = "from Package p where (p.packageStatus = 0 or p.packageStatus = 2) and p.storeTime < '"
				+ timestamp
				+ "'"
				+ buffer.toString()
				+ " order by p.storeTime desc";
		String hqlcount = "select count(p.packageId) from Package p where (p.packageStatus = 0 or p.packageStatus = 2) and p.storeTime < '"
				+ timestamp + "'" + buffer.toString();
		return new PageBean<Package>(curpage, pageSize,
				Integer.parseInt(queryDAO.queryUnique(hqlcount) + ""),
				queryDAO.queryByPage(hql, curpage, pageSize));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see Service.BoxAndPackageServiceInterface#take(int, int, int)
	 */
	@Override
	public void take(int terminalID, int boxNum, int type, int packageID,
			Agent agent) {
		boxDao.changeBoxStatus(terminalID, boxNum, 0, type, 0, packageID);
		Package p = packageDao.setPackageTaken(terminalID, boxNum);
		LogParcel logParcel = null;
		if (type == 1) {
			logParcel = new LogParcel(p, new Timestamp(new Date().getTime()),
					agent, "【远程开锁】了包裹", "");
		}
		if (type == 0) {
			logParcel = new LogParcel(p, new Timestamp(new Date().getTime()),
					agent, "【清空】了包裹", "");
		}
		logParcelDao.save(logParcel);
		if (agent.getUpload() == 1
				&& ("韵达快递".equals(p.getBelong()) || p.getBelong()
						.contains("汇通"))) {
//			AnJieRequestThread rnt = new AnJieRequestThread();
//			rnt.setUrl("http://42.121.192.78:8086/ourangel-box-rpc/terminalSystem/updatePackage.html");
//			rnt.setSign("c8db7d0e24e9a4ac3e42ec9c06ddc5f7");
//			rnt.setParcelId(String.valueOf(p.getPackageId()));
//			rnt.setParcelNum(p.getParcelId());
//			rnt.setParcelStatus(2);
//			rnt.setGetTime(p.getGetTime().toString());
//			Thread thread = new Thread(rnt);
//			thread.start();
		}
	}

	@Override
	public void takeGoods(int terminalID, int boxNum, int type, int goodsID,
			Agent agent) {
		Goods goods = goodsDao.getGoodsById(goodsID);
		if (type == 1) {
			goods.setIsForcedOpen("1");
			boxDao.changeBoxStatus(terminalID, boxNum, 3, type, goodsID, 0);
		} else {
			goods.setIsForcedOpen("2");
			boxDao.changeBoxStatus(terminalID, boxNum, 0, type, goodsID, 0);
			goods.setStatus("4");
			goods.setGetTime(new Timestamp(new Date().getTime()));
		}
		goodsDao.editGoods(goods);
		// Goods goods = goodsDao.getGoodsById(goodsID);
		// goods.setIsForcedOpen("1");
		// goodsDao.editGoods(goods);
		// boxDao.changeBoxStatus(terminalID, boxNum,1, type,goodsID,0);
	}

	@Override
	public void unTakenGoods(int terminalID, int boxNum, int type) {
		Goods goods = goodsDao.resetLatestGoods(terminalID, boxNum);
		boxDao.changeBoxStatus(terminalID, boxNum, 1, type, goods.getId(), 0);
		// Goods goods = goodsDao.getGoodsById(goodsID);
		// goods.setIsForcedOpen("1");
		// goodsDao.editGoods(goods);
		// boxDao.changeBoxStatus(terminalID, boxNum,1, type,goodsID,0);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see Service.BoxAndPackageServiceInterface#unTaken(int, int, int)
	 */
	@Override
	public void unTaken(int terminalID, int boxNum, int type, Agent agent) {
		Package p = packageDao.setPackageUnTaken(terminalID, boxNum);
		boxDao.setBoxOccupation(terminalID, boxNum, 0, p.getPackageId());
		LogParcel logParcel = new LogParcel(p, new Timestamp(
				new Date().getTime()), agent, "【反置位】了包裹", "");
		logParcelDao.save(logParcel);
		if (agent.getUpload() == 1
				&& ("韵达快递".equals(p.getBelong()) || p.getBelong()
						.contains("汇通"))) {
//			AnJieRequestThread rnt = new AnJieRequestThread();
//			rnt.setUrl("http://42.121.192.78:8086/ourangel-box-rpc/terminalSystem/updatePackage.html");
//			rnt.setSign("c8db7d0e24e9a4ac3e42ec9c06ddc5f7");
//			rnt.setParcelId(String.valueOf(p.getPackageId()));
//			rnt.setParcelNum(p.getParcelId());
//			rnt.setParcelStatus(0);
//			rnt.setGetTime(null);
//			Thread thread = new Thread(rnt);
//			thread.start();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see Service.BoxAndPackageServiceInterface#back(int, int, int)
	 */
	@Override
	public void back(int terminalID, int boxNum, int type) {
		boxDao.setBoxAvailable(terminalID, boxNum, type);
		packageDao.setPackageBack(terminalID, boxNum);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see Service.BoxAndPackageServiceInterface#dealPackage(java.util.List,
	 * Beans.Package, int)
	 */
	@Override
	public List<Package> dealPackage(List<Package> packages, Package p,
			int packageID, Agent agent) {
		p = packageDao.getPackageDetailsByID(packageID);
		boxDao.setBoxAvailable(p.getTerminal().getTerminalId(), p.getBoxId(), 0);
		// boxDao.changeBoxStatus(p.getTerminal().getTerminalId(), p.getBoxId(),
		// 0, 0);
		packages = packageDao.dealPackage(packageID, agent);
		LogParcel logParcel = new LogParcel(p, new Timestamp(
				new Date().getTime()), agent, "设置包裹为【已处理】", "");
		logParcelDao.save(logParcel);
		return packages;
	}

	@Override
	public List<Package> getStorePackage(int terminalID, int boxNum) {
		List<Package> packages = null;
		packages = packageDao.getPacakgeDetailsByBoxNum(terminalID, boxNum);
		return packages;
	}

	@Override
	public List<Goods> getStoreGoods(int terminalID, int boxNum) {
		List<Goods> goods = null;
		goods = goodsDao.getGoodsDetailsByBoxNum(terminalID, boxNum);
		return goods;
	}

	@Override
	public List<Terminal> getTerminalByBranch(int branchId) {
		List<Terminal> terminals = terminalDao
				.returnTermialByBranchID(branchId);
		return terminals;
	}

	@Override
	public List<Branch> getBranchByAgent(int agentId) {
		List<Branch> branchs = branchDao.getBranchByAgentId(agentId);
		return branchs;
	}

	/**
	 * 标记包裹
	 */
	@Override
	public void signParcel(String newPhone, Package p, int packageID,
			Agent agent, int problemID, int operate, int detained,
			String reason, String comment) {
		StringBuffer temp = new StringBuffer();
		p = packageDao.getPackageDetailsByID(packageID);
		if (operate == 1) {// 清空箱格
			p.setGetTime(new Timestamp(new Date().getTime()));
			p.setPackageStatus(5);
			packageDao.editPackage(p);
			// packageDao.setPackageTaken(p.getTerminal().getTerminalId(),
			// p.getBoxId());
			boxDao.changeBoxStatus(p.getTerminal().getTerminalId(),
					p.getBoxId(), 0, 2, 0, p.getPackageId());
			temp.append("【清空】了包裹，并且");
		}
		if (operate == 2) {// 远程开箱
			p.setGetTime(new Timestamp(new Date().getTime()));
			p.setPackageStatus(5);
			packageDao.editPackage(p);
			boxDao.changeBoxStatus(p.getTerminal().getTerminalId(),
					p.getBoxId(), 0, 1, 0, p.getPackageId());
			temp.append("【远程开锁】了包裹，并且");
		}
		if (operate == 3) {// 系统补发短信
			if (p.getUserPhone().equals(newPhone)) {
				temp.append("【重发了短信】，并且");
			} else {
				temp.append("【重发了短信】，将" + p.getUserPhone() + "改为" + newPhone
						+ "并且");
			}
			p.setUserPhone(newPhone);
			packageDao.editPackage(p);
			GetHelper
					.doHttpGet("http://112.124.59.126:8080/YouBoxApi/controller?funcID=0031&endMsg=（系统补发）&parcelId="
							+ p.getPackageId());
		}
		if (operate == 4) {// 锁定箱格
			packageDao.signPackage(packageID);
			boxDao.changeBoxStatus(p.getTerminal().getTerminalId(),
					p.getBoxId(), 2, 2, 0, packageID);
			temp.append("【锁定】了包裹，并且");
		}
		if (problemID == 1)
			temp.append("将包裹标记为【有空来取】");
		if (problemID == 2)
			temp.append("将包裹标记为【号码空号】");
		if (problemID == 3)
			temp.append("将包裹标记为【存错了】");
		if (problemID == 4)
			temp.append("将包裹标记为【未接电话】");
		if (problemID == 5)
			temp.append("将包裹标记为【空包】");
		if (problemID == 6)
			temp.append("将包裹标记为【退件】");
		if (problemID == 7) {
			temp.append("将包裹标记为【没收到短信】");
		}
		if (problemID == 8)
			temp.append("将包裹标记为【门没打开】");
		if (problemID == 9)
			temp.append("将包裹标记为【取件码失效】");
		if (problemID == 10)
			temp.append("将包裹标记为【系统维护中】");
		if (problemID == 11)
			temp.append("将包裹标记为【疑似丢件】");
		if (problemID == 12) {
			temp.append("将包裹标记为【手机号码输错】");
			Courier courier = p.getCourier();
			courier.setErrorTimes(courier.getErrorTimes().add(
					new BigInteger("1")));
			courierDao.edit(courier);
		}
		LogParcel logParcel = new LogParcel(p, new Timestamp(
				new Date().getTime()), agent, temp.toString(), comment);
		logParcelDao.save(logParcel);
		p.setDetained(detained);
		packageDao.editPackage(p);// 修改滞留等级
		// if (problemID == 7) {
		// MsgProblem msgProblem = new MsgProblem(p.getUserPhone(), p
		// .getTerminal().getBranch().getSmsPlatform()
		// + "", smsStatusDao.getByParcelID(packageID).get(0)
		// .getContent(), reason, admin.getUsername());
		// msgProblemDao.save(msgProblem);
		// }
	}

	/**
	 * 解锁包裹
	 */
	@Override
	public void unLockParcel(Package p, int packageID, Agent agent) {
		p = packageDao.getPackageDetailsByID(packageID);
		boxDao.changeBoxStatus(p.getTerminal().getTerminalId(), p.getBoxId(),
				1, 1, 0, p.getPackageId());
		packageDao.unLockPackage(packageID);
		LogParcel logParcel = new LogParcel(p, new Timestamp(
				new Date().getTime()), agent, "【解锁】了包裹", "");
		logParcelDao.save(logParcel);
	}
}
